﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TyNetCoreBlog.Helpers;
using TyNetCoreBlog.Models.Dto.User;
using TyNetCoreBlog.Repository.RepositoryWrapper;
using static TyNetCoreBlog.Helpers.ResponseMsg;

namespace TyNetCoreBlog.Controllers
{
    [Route("api/users")]
    [EnableCors("any")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IRepositoryWrapper _repositoryWrapper;
        private readonly IMapper _mapper;

        public UserController(IRepositoryWrapper repositoryWrapper, IMapper mapper)
        {
            this._repositoryWrapper = repositoryWrapper ?? throw new ArgumentNullException(nameof(repositoryWrapper));
            this._mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }

        /// <summary>
        /// 通过ID获取用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{userId}")]
        public async Task<ActionResult<UserDto>> GetUserInfo(int userId)
        {
            var user = await _repositoryWrapper.User.GetUserInfoAsync(userId);
            if (user == null)
            {
                return NotFound(new ResponseMsg(ApiStatus.NotFound));
            }
            var us = _mapper.Map<UserDto>(user);
            return Ok(new ResponseMsg(ApiStatus.OK, us));
        }


        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<UserDto>>> GetUsers()
        {
            var users = await _repositoryWrapper.User.GetAllAsync();
            var userDtoList = _mapper.Map<IEnumerable<UserDto>>(users).ToList();
            return Ok(new ResponseMsg(ApiStatus.OK, userDtoList));
        }

    }
}
